import React, { useEffect, useState } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import UserProfile from "../components/UserProfile.js";
import VideoYouLike from "../components/VideoYouLike.js";
import VideoUpload from "../components/VideoUpload.js";
import Subscribe from "../components/Subscribe.js";
import "../pagesCss/UserProfileCss.css";

const UserProfilePage = () => {
  const [info, setInfo] = useState(null); // 用于存储用户信息
  const [error, setError] = useState(null); // 错误信息

  // 在组件加载时获取用户信息
  useEffect(() => {
    const fetchInfo = async () => {
      const token = Cookies.get("token"); // 从 cookies 获取 token
      console.log("token:", token);
      if (!token) {
        setError("Please login first");
        return;
      }

      try {
        const response = await axios.get("http://localhost:8080/user/info", {
          params: {
            token: token,
          },
        });
        setInfo(response.data); // 获取到用户信息
        console.log("response.data:", response.data.data.user);
      } catch (error) {
        setError("Failed to fetch user info");
        console.error("error:", error);
      }
    };

    fetchInfo();
  }, []); // 空数组表示只在组件加载时调用一次

  return (
    <div className="user-profile">
      {info && info.data.user ? (
        <UserProfile
          username={info.data.user.name}
          userAvatar={info.data.user.imgurl}
          description={info.data.user.descrip} // 添加描述信息
        />
      ) : (
        <div></div> // 当 info 为空时显示空的 div
      )}

      <main className="content">
        {info && (
          <>
            <VideoYouLike videos={info.data.likedVideos} />
            <VideoUpload videos={info.data.uploadedVideos} />
            <Subscribe likedUpMasters={info.data.likedUpMasters} />
          </>
        )}
      </main>
    </div>
  );
};

export default UserProfilePage;
